import React, { useEffect, useMemo, useState } from 'react';
import { Card, Grid, List, Skeleton, Statistic, Tag, Typography } from '@arco-design/web-react';
import useLocale from '@/utils/useLocale';
import { IconArrowFall, IconArrowRise } from '@arco-design/web-react/icon';
import instance from '@/utils/request';
import moment from 'moment';
import { AlarmAnalysisResponse, AlarmRecordResponse } from '@/constants/type';
import { Axis, Chart, Interval, Legend, Line, LineAdvance, Tooltip } from 'bizcharts';
import { resolveAlarmLevel, resolveContinuingName } from '@/constants/functions';
import { chartColors } from '@/constants/constants';
import { formatMillisecondsToTime } from '@/utils/time';

const { Row, Col } = Grid;

const locale = {
  'en-US': {},
  'zh-CN': {
    'title.alarm.today.count': '今日报警(次数)',
    'title.alarm.today.count.compare': '较昨日',
    'title.alarm.today.duration': '今日报警(时长)',
    'title.alarm.today.duration.compare': '较昨日',
    'title.alarm.latest': '实时报警',
    'title.alarm.realtime': '实时报警',
    'title.alarm.trend': '报警趋势'
  }
};

const AlarmCenter = () => {
  const t = useLocale(locale);
  const [loadingAlarmToday, setLoadingAlarmToday] = useState<boolean>(false);
  const [loadingAlarmTrend, setLoadingAlarmTrend] = useState<boolean>(false);
  const [alarmTodayData, setAlarmTodayData] = useState<AlarmAnalysisResponse[]>([]);
  const [alarmToday, setAlarmToday] = useState<Partial<AlarmAnalysisResponse>>();
  const [alarmYesToday, setAlarmYesToday] = useState<Partial<AlarmAnalysisResponse>>();
  const [loadingLatestAlarmList, setLoadingLatestAlarmList] = useState<boolean>(false);
  const [latestAlarmList, setLatestAlarmList] = useState<AlarmRecordResponse[]>([]);
  const [alarmTrendData, setAlarmTrendData] = useState<AlarmAnalysisResponse[]>([]);
  const getLatestAlarmList = useMemo(() => {
    return latestAlarmList.map((it, idx) =>
      <Row key={'latest_alarm_' + idx}>
        <Col span={5}>
          <Typography.Text>{it?.alarmConfig.name}</Typography.Text>
        </Col>
        <Col span={4}>
          <Row gutter={12}>
            <Tag style={{ marginLeft: '0.5rem' }} color={'#fc00ca'}>{resolveAlarmLevel(it?.alarmConfig?.level)}</Tag>
            {it?.continuing && <Tag>{resolveContinuingName(it?.continuing)}</Tag>}
          </Row>
        </Col>
        <Col span={5}>
          <Typography.Text>
            {it?.device?.name}
          </Typography.Text>
        </Col>
        <Col span={2}>
          <Typography.Text>
            {formatMillisecondsToTime(it?.duration)}
          </Typography.Text>
        </Col>
        <Col span={3}>
          <Typography.Text>
            {moment(it?.startTime).format('YYYY-MM-DD')}
          </Typography.Text>
        </Col>
        <Col span={5}>
          <Typography.Text>
            {moment(it?.startTime).format('HH:MM:SS')} - {moment(it?.endTime).format('HH:MM:SS')}
          </Typography.Text>
        </Col>
      </Row>);
  }, [latestAlarmList]);

  useEffect(() => {
    const fetchTotalAlarm = () => {
      setLoadingAlarmToday(true);
      instance
        .post('/api/alarm/analysis/daily', {
          query: {
            recordDateStart: moment().add(-7, 'day').format('YYYY-MM-DD'),
            recordDateEnd: moment().format('YYYY-MM-DD')
          }
        })
        .then((res) => {
          if (res.data.code === 200) {
            setAlarmTodayData(res.data.data);
            if ((res.data.data || []).length >= 2) {
              const today = res.data.data[res.data.data.length - 1];
              setAlarmToday(today);
              const yestoday = res.data.data[res.data.data.length - 2];
              setAlarmYesToday({
                ...yestoday,
                count: (today.count - yestoday.count),
                duration: (today.duration - yestoday.duration)
              });
            }
          }
        }).finally(() => setLoadingAlarmToday(false));
    };
    const fetchLatestAlarmRecord = () => {
      setLoadingLatestAlarmList(true);
      instance
        .post('/api/alarm/record/page', {
          pager: {
            pageNumber: 1,
            pageSize: 10
          },
          query: {
            recordDateStart: moment().add(-7, 'day').format('YYYY-MM-DD'),
            recordDateEnd: moment().format('YYYY-MM-DD')
          },
          sort: [
            {
              property: 'lastModifiedDate',
              direction: 'desc'
            }
          ]
        })
        .then((res) => {
          if (res.data.code === 200) {
            setLatestAlarmList(res.data.data);
          }
        }).finally(() => setLoadingLatestAlarmList(false));
    };
    const fetchAlarmTrend = () => {
      setLoadingAlarmTrend(true);
      instance
        .post('/api/alarm/analysis/list', {
          query: {
            recordDateStart: moment().add(-7, 'day').format('YYYY-MM-DD'),
            recordDateEnd: moment().format('YYYY-MM-DD')
          }
        })
        .then((res) => {
          if (res.data.code === 200) {
            const result = [];
            res.data.data.forEach(it => {
              result.push({
                type: it?.alarmConfig?.name,
                recordDate: it.recordDate,
                duration: it.duration,
                count: it.count
              });
            });
            setAlarmTrendData(result);
          }
        }).finally(() => setLoadingAlarmTrend(false));
    };
    fetchTotalAlarm();
    fetchLatestAlarmRecord();
    fetchAlarmTrend();
  }, []);

  return (
    <Row gutter={12}>
      <Col span={12}>
        <Row gutter={12}>
          <Col span={12}>
            <Card>
              <Typography.Title heading={6}>{t['title.alarm.today.count']}</Typography.Title>
              {!!loadingAlarmToday
                ? (<Skeleton animation />)
                : (<Row gutter={12}>
                  <Col span={10}>
                    <Row>
                      <Col span={24}>
                        <Statistic styleValue={{ fontSize: '2rem' }} value={alarmToday?.count} countUp />
                      </Col>
                      <Col span={24}>
                        <Statistic
                          styleValue={{ fontSize: '1.1rem', color: alarmYesToday?.count > 0 ? '#ee4d38' : '#00b534' }}
                          prefix={<Typography.Text
                            style={{
                              color: 'grey',
                              fontSize: '0.8rem'
                            }}>{t['title.alarm.today.count.compare']}</Typography.Text>}
                          countUp
                          value={Math.abs(alarmYesToday?.count)}
                          suffix={alarmYesToday?.count > 0
                            ? <IconArrowRise style={{ color: '#ee4d38' }} />
                            : <IconArrowFall style={{ color: '#00b534' }} />} />
                      </Col>
                    </Row>
                  </Col>
                  <Col span={14}>
                    <Chart padding={[0, 0, 10, 0]} autoFit height={70} data={alarmTodayData}>
                      <Axis visible={false} />
                      <LineAdvance shape="smooth" position="recordDate*count"></LineAdvance>
                    </Chart>
                  </Col>
                </Row>)}
            </Card>
          </Col>
          <Col span={12}>
            <Card>
              <Typography.Title heading={6}>{t['title.alarm.today.duration']}</Typography.Title>
              {!!loadingAlarmToday
                ? (<Skeleton animation />)
                : (<Row gutter={12}>
                  <Col span={10}>
                    <Row>
                      <Col span={24}>
                        <Statistic styleValue={{ fontSize: '2rem' }} value={alarmToday?.duration} format="HH:mm:ss"
                                   countUp />
                      </Col>
                      <Col span={24}>
                        <Statistic
                          styleValue={{
                            fontSize: '1.1rem',
                            color: alarmYesToday?.duration > 0 ? '#ee4d38' : '#00b534'
                          }}
                          prefix={<Typography.Text
                            style={{
                              color: 'grey',
                              fontSize: '0.8rem'
                            }}>{t['title.alarm.today.duration.compare']}</Typography.Text>}
                          countUp
                          format="HH:mm:ss"
                          value={alarmYesToday?.duration}
                          suffix={alarmYesToday?.duration > 0
                            ? <IconArrowRise style={{ color: '#ee4d38' }} />
                            : <IconArrowFall style={{ color: '#00b534' }} />} />
                      </Col>
                    </Row>
                  </Col>
                  <Col span={14}>
                    <Chart padding={[0, 0, 10, 0]} autoFit height={70} data={alarmTodayData}>
                      <Axis visible={false} />
                      <LineAdvance shape="smooth" position="recordDate*duration"></LineAdvance>
                    </Chart>
                  </Col>
                </Row>)}
            </Card>
          </Col>
        </Row>
        <Row>
          <Col span={24} style={{ marginTop: '12px' }}>
            <Card>
              <Typography.Title heading={6}>{t['title.alarm.trend']}</Typography.Title>
              {!!loadingAlarmTrend
                ? (<Skeleton animation />)
                : (<Chart padding={[20, 50, 20, 80]} autoFit height={380} data={alarmTrendData}>
                    <Line shape="smooth" position="recordDate*duration" color={['type', chartColors]}>
                    </Line>
                    <Interval position={'recordDate*count'} size={24} color={['type', chartColors]} />
                    <Legend position={'top'} />
                    <Tooltip shared showContent></Tooltip>
                  </Chart>
                )}
            </Card>
          </Col>
        </Row>
      </Col>
      <Col span={12}>
        <Card>
          <Typography.Title heading={6}>{t['title.alarm.latest']}</Typography.Title>
          {!!loadingLatestAlarmList
            ? (<Skeleton animation />)
            : (<List
              dataSource={getLatestAlarmList}
              render={(item, index) => <List.Item key={index}>{item}</List.Item>}
            />)}
        </Card>
      </Col>
    </Row>
  );

};

export default AlarmCenter;